package com.example.demo.service;

import com.example.demo.dao.AccountMapper;
import com.example.demo.dao.AuthorityMapper;
import com.example.demo.enumutil.AccountStatusEnum;
import com.example.demo.pojo.Account;
import com.example.demo.pojo.GrantedAuthorityImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * <h3>reqister</h3>
 * <p>重定义Security登陆逻辑</p>
 *
 * @author : chenjunjie
 * @date : 2021-06-21 16:13
 **/
@Repository
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    AuthorityMapper authorityMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = accountMapper.findByName(username);
        List<String> authoritys = authorityMapper.getAuthoritys(account.getRoleId());
        account.setAuthorities(getAuthoritys(authoritys));

        if((AccountStatusEnum.DISABLE.getStatus()).equals(account.getStatus())) {
            account.setEnabled(false);
        }

        return account;
    }

    /**
     * 解析权限信息
     * @param authorityList
     * @return
     */
    public List<GrantedAuthority> getAuthoritys(List<String> authorityList){
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        for (String  authority: authorityList) {
            authorities.add(new GrantedAuthorityImpl(authority));
        }

        return authorities;
    }
}
